<template>
    <div class="e-form">
        <BillTop title="外协台账编辑" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="进场验收"
                    name="siteAcceptance"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="检查记录"
                    name="checkLog"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="进出场记录"
                    name="turnoverLog"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                ref="form"
                                :model="formData"
                                label-width="200px"
                                :rules="rules"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="设备编号：">
                                            <span>{{
                                                formData.equipmentNo
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="外协单位："
                                            prop="supplierName"
                                        >
                                            <el-input
                                                v-model="formData.supplierName"
                                                readonly
                                            >
                                                <i
                                                    slot="suffix"
                                                    class="
                                                        el-input__icon
                                                        el-icon-document-copy
                                                    "
                                                    @click="selectUnit"
                                                ></i>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="设备名称："
                                            prop="equipmentName"
                                        >
                                            <el-input
                                                v-model="formData.equipmentName"
                                                readonly
                                            >
                                                <i
                                                    slot="suffix"
                                                    class="
                                                        el-input__icon
                                                        el-icon-document-copy
                                                    "
                                                    @click="selectEquip"
                                                ></i>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="规格型号：" prop="specificationModel">
                                            <el-input
                                                v-model="
                                                    formData.specificationModel
                                                "
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-col :span="12">
                                            <el-form-item label="计量单位：">
                                                <span>{{ formData.unit }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="操作手：">
                                            <el-input
                                                v-model="formData.operatorName"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="进场时间："
                                            prop="enterDate"
                                        >
                                            <el-date-picker
                                                v-model="formData.enterDate"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="退场时间："
                                            prop="exitDate"
                                        >
                                            <el-date-picker
                                                v-model="formData.exitDate"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="使用地点："
                                            prop="useSite"
                                        >
                                            <el-input
                                                v-model="formData.useSite"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="外协设备来源："
                                            prop="equipmentSource"
                                        >
                                            <el-select
                                                v-model="
                                                    formData.equipmentSource
                                                "
                                            >
                                                <el-option
                                                    :value="item.value"
                                                    :label="item.label"
                                                    v-for="(
                                                        item, index
                                                    ) in equipmentSource"
                                                    :key="index"
                                                ></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="出租/销售单位：">
                                            <el-input
                                                v-model="formData.leaseSaleUnit"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="已付租赁/设备费（元）："
                                            prop="paid"
                                        >
                                            <el-input
                                                v-model="formData.paid"
                                                v-enter-float="{
                                                    set: this,
                                                    val: 'formData',
                                                    key: 'paid'
                                                }"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="车牌编号："
                                            prop="plateNo"
                                        >
                                            <el-input
                                                v-model="formData.plateNo"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="未付租赁/设备费（元）："
                                            prop="unpaid"
                                        >
                                            <el-input
                                                v-model="formData.unpaid"
                                                v-enter-float="{
                                                    set: this,
                                                    val: 'formData',
                                                    key: 'unpaid'
                                                }"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="进退场状态："
                                            prop="enterExitState"
                                        >
                                            <el-select
                                                v-model="
                                                    formData.enterExitState
                                                "
                                            >
                                                <el-option
                                                    :value="+item.value"
                                                    :label="item.label"
                                                    v-for="(
                                                        item, index
                                                    ) in enterExitStatus"
                                                    :key="index"
                                                ></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="所属机构：">
                                            <span>{{ formData.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="siteAcceptanceCon" class="con">
                        <div class="tabs-title" id="siteAcceptance">
                            进场验收
                        </div>
                        <el-tabs
                            :max-height="$store.state.tableHeight"
                            :class="'childTab ' + childTabClass"
                            tab-position="left"
                            v-model="tabsNameChild"
                            @tab-click="onChangeTab"
                        >
                            <el-tab-pane
                                label="基本信息"
                                name="siteBaseInfo"
                                :disabled="clickTabFlag"
                            ></el-tab-pane>
                            <el-tab-pane
                                label="附件信息"
                                name="attach"
                                :disabled="clickTabFlag"
                            ></el-tab-pane>
                            <div>
                                <div id="siteBaseInfoCon" class="con">
                                    <div class="tabs-title" id="siteBaseInfo">
                                        基本信息
                                    </div>
                                    <el-form
                                        ref="formSite"
                                        :model="formSiteBaseInfo"
                                        label-width="220px"
                                        :rules="rulesSiteBaseInfo"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收人："
                                                    prop="acceptor"
                                                >
                                                    <el-input
                                                        v-model="
                                                            formSiteBaseInfo.acceptor
                                                        "
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收日期："
                                                    prop="billDate"
                                                >
                                                    <el-date-picker
                                                        v-model="
                                                            formSiteBaseInfo.billDate
                                                        "
                                                        type="date"
                                                        placeholder="选择日期"
                                                        value-format="yyyy-MM-dd"
                                                        :clearable="false"
                                                    >
                                                    </el-date-picker>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="安全装置是否满足施工要求："
                                                    prop="isSafetySatisfy"
                                                >
                                                    <el-radio-group
                                                        v-model="
                                                            formSiteBaseInfo.isSafetySatisfy
                                                        "
                                                    >
                                                        <el-radio :label="0"
                                                            >是</el-radio
                                                        >
                                                        <el-radio :label="1"
                                                            >否</el-radio
                                                        >
                                                    </el-radio-group>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="环保是否满足施工要求："
                                                    prop="isEnvironmentalSatisfy"
                                                >
                                                    <el-radio-group
                                                        v-model="
                                                            formSiteBaseInfo.isEnvironmentalSatisfy
                                                        "
                                                    >
                                                        <el-radio :label="0"
                                                            >是</el-radio
                                                        >
                                                        <el-radio :label="1"
                                                            >否</el-radio
                                                        >
                                                    </el-radio-group>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="24">
                                                <el-form-item
                                                    label="验收概述："
                                                    prop="remarks"
                                                >
                                                    <el-input
                                                        type="textarea"
                                                        v-model="
                                                            formSiteBaseInfo.remarks
                                                        "
                                                        placeholder="请输入内容"
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>

                                <div id="attachCon" class="con">
                                    <div class="tabs-title" id="attach">
                                        附件信息
                                    </div>
                                    <attach-comp
                                        :relationId="attachId"
                                        bucketName="facilityaccount"
                                    />
                                </div>
                            </div>
                        </el-tabs>
                    </div>

                    <div id="checkLogCon" class="con">
                        <div class="tabs-title" id="checkLog">检查记录</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button
                                            class="btn-greenYellow"
                                            @click="checkLogAdd"
                                            >新增</el-button
                                        >
                                        <el-button
                                            class="btn-greenYellow"
                                            @click="checkLogEdit"
                                            :disabled="checkLog.length === 0"
                                            >编辑</el-button
                                        >
                                    </div>
                                </div>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="checkLogTable"
                                :data="checkLogListCopy"
                                border
                                style="width: 100%"
                                @selection-change="checkLogSelect"
                                v-sortTable="{ 'tableData': checkLogListCopy, '_this': this, 'ref': 'checkLogTable' }"
                            >
                                <el-table-column
                                    show-overflow-tooltip
                                    type="selection"
                                    width="55"
                                    v-if="checkLogListCopy.length > 0"
                                >
                                </el-table-column>
                                <el-table-column
                                    fixed
                                    type="index"
                                    label="序号"
                                    width="80"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row, $index }">
                                        <div class="handle">
                                            <div style="cursor: pointer">
                                                <img
                                                    src="@/assets/btn/delete.png"
                                                    @click="
                                                        handleDelete(
                                                            row,
                                                            $index
                                                        )
                                                    "
                                                />
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="checkDate"
                                    label="检查日期"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="checkType"
                                    label="检查类型"
                                    min-width="200"
                                    show-overflow-tooltipd
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{
                                            row.checkType || row.checkType === 0
                                                ? checkType[row.checkType].label
                                                : ''
                                        }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="checkRemarks"
                                    label="检查内容"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="checker"
                                    label="检查人"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="recorder"
                                    label="记录人"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="turnoverLogCon" class="con">
                        <div class="tabs-title" id="turnoverLog">
                            进出场记录
                        </div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button
                                            class="btn-greenYellow"
                                            @click="turnoverLogAdd"
                                            >新增</el-button
                                        >
                                        <el-button
                                            class="btn-greenYellow"
                                            @click="turnoverLogEdit"
                                            :disabled="turnoverLog.length == 0"
                                            >编辑</el-button
                                        >
                                    </div>
                                </div>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="turnoverLogListCopy"
                                border
                                style="width: 100%"
                                @selection-change="turnoverLogSelect"
                                v-sortTable="{ 'tableData': turnoverLogListCopy, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column
                                    show-overflow-tooltip
                                    type="selection"
                                    width="55"
                                    v-if="turnoverLogListCopy.length > 0"
                                >
                                </el-table-column>
                                <el-table-column
                                    fixed
                                    type="index"
                                    label="序号"
                                    width="80"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row, $index }">
                                        <div class="handle">
                                            <div style="cursor: pointer">
                                                <img
                                                    src="@/assets/btn/delete.png"
                                                    @click="
                                                        handleTurnoverDelete(
                                                            row,
                                                            $index
                                                        )
                                                    "
                                                />
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="useOrg"
                                    label="使用单位"
                                    min-width="200"
                                    show-overflow-tooltip
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="enterDate"
                                    label="进场时间"
                                    min-width="200"
                                    show-overflow-tooltipd
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="enterDate"
                                    label="退场时间"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <span class="tip"
                ><span style="color: red; margin-right: 0">*</span
                >为必填项</span
            >
            <el-button type="primary" class="btn-blue" size="small" v-debounce
                >打印</el-button
            >
            <el-button type="primary" class="btn-blue" size="small" v-debounce
                >打印二维码</el-button
            >
            <el-button
                type="primary"
                class="btn-blue"
                @click="saveAll"
                size="small"
                v-debounce
                >保存</el-button
            >
            <el-button
                type="primary"
                class="btn-delete"
                size="small"
                @click="deleteBillid"
                v-debounce
                >删除</el-button
            >
            <el-button size="small" @click="handleClose" v-debounce
                >取消</el-button
            >
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import request from '@/api/equip/equipAccount.js'
import { openAppClient, hideLoading, showLoading } from '@/utils/common'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import { selectDataClient } from '@/utils/common'
import ossRequest from '@/api/oss/oss.js'
import { selectOutsourceUnit } from '@/api/equip/popupCallback.js'
export default {
    data () {
        return {
            res: '',
            isBatch: [
                {
                    flag: false,
                    batch: '进入批量管理'
                },
                {
                    flag: false,
                    batch: '进入批量管理'
                }
            ],
            tabsName: 'baseInfo',
            clickId: 'baseInfo',
            tabsNameChild: '',
            childTabClass: '',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            selectEquipVisible: false,
            tableData: [],
            //基本信息
            formData: {
                billId: '',
                categoryId: '',
                categoryName: '',
                enrollDate: '',
                enterDate: '',
                enterExitState: null,
                equipmentCondition: '',
                equipmentId: '',
                equipmentName: '',
                equipmentNo: '',
                equipmentSource: '',
                exitDate: '',
                founderId: '',
                founderName: '',
                isBack: true,
                leaseAccountId: '',
                leaseSaleUnit: '',
                operatorName: '',
                orgId: '',
                orgName: '',
                paid: null,
                plateNo: '',
                shortCode: '',
                specificationModel: '',
                supplierId: '',
                supplierName: '',
                unit: '',
                unpaid: null,
                useSite: '',
                contractId: ''
            },
            rules: {
                supplierName: [
                    {
                        required: true,
                        message: '请选择外协单位',
                        trigger: 'change'
                    }
                ],
                equipmentName: [
                    {
                        required: true,
                        message: '请选择设备名称',
                        trigger: 'change'
                    }
                ],
                enterDate: [
                    {
                        required: true,
                        message: '请选择进场时间',
                        trigger: 'change'
                    },
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            if (this.formData.exitDate) {
                                const enterDate = new Date(
                                    this.formData.enterDate
                                ).getTime() //进场时间
                                const exitDate = new Date(
                                    this.formData.exitDate
                                ).getTime() //退场时间
                                if (enterDate > exitDate) {
                                    callback(
                                        new Error('进场时间不能大于退场时间')
                                    )
                                } else {
                                    callback()
                                }
                            } else {
                                callback()
                            }
                        },
                        trigger: ['blur', 'change']
                    }
                ],
                exitDate: [
                    {
                        required: false,
                        validator: (rule, value, callback) => {
                            if (this.formData.enterDate) {
                                const enterDate = new Date(
                                    this.formData.enterDate
                                ).getTime() //进场时间
                                const exitDate = new Date(
                                    this.formData.exitDate
                                ).getTime() //退场时间
                                if (enterDate > exitDate) {
                                    callback(
                                        new Error('退场时间不能小于进场时间')
                                    )
                                } else {
                                    callback()
                                }
                            } else {
                                callback()
                            }
                        },
                        trigger: ['blur', 'change']
                    }
                ],
                useSite: [
                    {
                        required: true,
                        message: '请填写使用地点',
                        trigger: 'blur'
                    }
                ],
                equipmentSource: [
                    {
                        required: true,
                        message: '请选择外协设备来源',
                        trigger: 'change'
                    }
                ],
                paid: [
                    {
                        required: true,
                        message: '请填写已付租赁/设备费（元）',
                        trigger: 'blur'
                    }
                ],
                plateNo: [
                    { required: true, message: '请填写车牌号', trigger: 'blur' }
                ],
                unpaid: [
                    {
                        required: true,
                        message: '请填写未付租赁/设备费（元）',
                        trigger: 'blur'
                    }
                ],
                enterExitState: [
                    {
                        required: true,
                        message: '请选择进退场状态',
                        trigger: 'change'
                    }
                ],
                specificationModel: [
                    {
                        required: true,
                        message: '请填写规格型号',
                        trigger: 'blur'
                    }
                ]
            },
            //进场验收基本信息
            formSiteBaseInfo: {
                acceptor: '',
                billDate: '',
                billId: this.$route.query.billid,
                id: '',
                isEnvironmentalSatisfy: null,
                isSafetySatisfy: null,
                remarks: ''
            },
            //进场验收基本信息验证
            rulesSiteBaseInfo: {
                acceptor: [
                    { required: true, message: '请填写验收人', trigger: 'blur' }
                ],
                billDate: [
                    {
                        required: true,
                        message: '请选择验收日期',
                        trigger: 'change'
                    }
                ],
                isSafetySatisfy: [
                    {
                        required: true,
                        message: '请选择安全装置是否满足施工要求',
                        trigger: 'change'
                    }
                ],
                isEnvironmentalSatisfy: [
                    {
                        required: true,
                        message: '请选择环保是否满足施工要求',
                        trigger: 'change'
                    }
                ],
                remarks: [
                    {
                        required: true,
                        message: '请填写验收概述',
                        trigger: 'blur'
                    }
                ],
            },
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            maintenanceLogDtlListCopy: [],
            checkLogList: [], //检查记录
            checkLogListCopy: [],
            turnoverLogList: [], //进出场记录
            turnoverLogListCopy: [],
            isErrorMsg: true, //是否提醒错误信息
            currentRow: {},
            billid: this.$route.query.billid,
            checkLog: [], //检查记录选择项
            turnoverLog: [], //进出场记录选择项
            isNewAdd: true //进场验收判断是新增还是编辑
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            maintenanceType: state => state.equip.equipData.maintenanceType, //维保类型
            unitMeasure: state => state.equip.equipData.unitMeasure, //计量单位
            equipmentSource: state => state.equip.equipData.equipmentSource, //外协设备来源
            enterExitStatus: state => state.equip.equipData.enterExitStatus, //进退场状态
            checkType: state => state.equip.equipData.checkType //检查类型
        }),
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value === param)
                return obj ? obj.label : ''
            }
        },
        //当前单据状态
        state () {
            return this.formData.state
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.$route.query.billid
        }
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        }
    },
    components: {
        AttachComp
    },
    created () {
        this.userId = localStorage.getItem('userId')
        this.getDicValue()
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            ['siteAcceptance', 'siteBaseInfo', 'attach'],
            'checkLog',
            'turnoverLog'
        ]
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //当点击的tab有子tab时做滚动逻辑
            if (this.clickTabFlag && arr.find(x => x === this.clickId)) {
                this.childTabClass = '' //无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if (item instanceof Array) {
                        //const prevHeight = document.getElementById(item[0]).offsetHeight + document.getElementById(item[0]).nextSibling.offsetHeight//因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                        arr = item.map((x, i) => {
                            if (i === 0) {
                                return document.getElementById(x).offsetTop
                            } else {
                                return (
                                    document.getElementById(x).offsetTop +
                                    document.getElementById(item[0]).offsetTop
                                )
                            }
                        })
                        return arr
                    } else {
                        itemTop = document.getElementById(item).offsetTop
                        return itemTop
                    }
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if ($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for (let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if (scrollTop + 1 >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if (scrollTop + 1 >= item[0]) {
                        curLocal = i
                        break
                    }
                } else {
                    let item = $idsTop[i]
                    if (scrollTop + 1 >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if (arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.tabsNameChild = arr[curLocal][curLocalChild]
            } else {
                this.tabsName = arr[curLocal]
            }
            //动态改变二级选项卡类名
            arr.forEach((item, index) => {
                if (item instanceof Array) {
                    let tabNavHeight = document.querySelector(
                        '.childTab .el-tabs__nav'
                    )
                        ? document.querySelector('.childTab .el-tabs__nav')
                            .offsetHeight
                        : 0
                    if (scrollTop + 1 >= $idsTop[index + 1] - tabNavHeight) {
                        this.childTabClass = 'childTab2'
                    } else if (scrollTop <= $idsTop[index][1]) {
                        this.childTabClass = ''
                    } else {
                        this.childTabClass = 'childTab1'
                    }
                }
            })
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if (item instanceof Array) {
                    //const prevHeight = document.getElementById(item[0]).offsetHeight + document.getElementById(item[0]).nextSibling.offsetHeight//因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                    arr = item.map((x, i) => {
                        if (i === 0) {
                            return document.getElementById(x).offsetTop
                        } else {
                            return (
                                document.getElementById(x).offsetTop +
                                document.getElementById(item[0]).offsetTop
                            )
                        }
                    })
                    return arr
                } else {
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        //跳转到明细
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //是否进入批量操作
        batchOperation (name) {
            switch (name) {
            case 'checkLog':
                this.isBatch[0].flag = !this.isBatch[0].flag
                if (this.isBatch[0].flag) {
                    this.isBatch[0].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                } else {
                    this.isBatch[0].batch = '进入批量管理'
                }
                break
            case 'turnoverLog':
                this.isBatch[1].flag = !this.isBatch[1].flag
                if (this.isBatch[1].flag) {
                    this.isBatch[1].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                } else {
                    this.isBatch[1].batch = '进入批量管理'
                }
                break
            }
        },
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setMaintenanceType') //更新维保类型
            this.$store.dispatch('equip/setUnitMeasur')
        },
        //初始化数据
        init () {
            showLoading()
            Promise.all([
                this.getInfo(),
                this.getSiteBaseInfo(),
                this.getCheckLog(),
                this.getTurnoverRecord()
            ]).finally(() => {
                hideLoading()
            })
        },
        //基本信息查询
        getInfo () {
            request.outAccountBaseInfo(this.billid).then(res => {
                this.formData = res
            })
        },
        //进场验收基本信息查询
        getSiteBaseInfo () {
            request.outAccountAcceptorBase(this.billid).then(res => {
                if (res.data === null) {
                    this.isNewAdd = true
                } else {
                    this.isNewAdd = false
                    this.formSiteBaseInfo = res
                }
            })
        },
        //检查记录查询
        getCheckLog () {
            request.outAccountCheckRecord(this.billid).then(res => {
                this.checkLogListCopy = [...res]
                this.checkLogList = res
            })
        },
        //进出场记录查询
        getTurnoverRecord () {
            request.outAccountTurnoverRecord(this.billid).then(res => {
                this.turnoverLogListCopy = [...res]
                this.turnoverLogList = res
            })
        },
        //============基本信息=============
        //选择设备
        selectEquip () {
            let json = {
                categoryId: '00000',
                isUpdate: false,
                keyword: ''
            }
            selectDataClient({
                SelectServiceToken:
                    '/facilitybase/equipment/getEquipmentCategoryAll', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify(json), // 接口参数
                Title: '设备基础库' // 标题
            }).then(res => {
                let item = res[0]
                this.formData.unit = item.unit //计量单位
                this.formData.equipmentName = item.equipmentName //设备编号
                this.formData.equipmentId = item.equipmentId //设备id
            })
        },
        //选择外协单位
        selectUnit () {
            let ids = this.formData.contractId
                ? [this.formData.contractId]
                : []
            selectOutsourceUnit(ids, this.userInfo.orgInfo.orgId).then(res => {
                this.formData.supplierName = res[0].secondPartyName
                this.formData.supplierId = res[0].secondPartyId
                this.formData.contractId = res[0].contractId
            })
        },
        //============检查记录=============
        /**新增 */
        checkLogAdd () {
            openAppClient(
                `/outAccountCheckLogAdd?billid=${this.billid}&isNewAdd=true`,
                '外协台账检查记录新增',
                () => {
                    this.getCheckLog()
                },
                null,
                () => {
                    this.getCheckLog()
                }
            )
        },
        //编辑
        checkLogEdit () {
            if (this.checkLog.length > 1) {
                this.clientPop('err', '一次只能选择一条数据！')
            } else {
                this.setAuditParams({ id: this.checkLog[0].id })
                openAppClient(
                    `/outAccountCheckLogAdd?billid=${this.billid}&isNewAdd=false`,
                    '外协台账检查记录编辑',
                    () => {
                        this.getCheckLog()
                    },
                    null,
                    () => {
                        this.getCheckLog()
                    }
                )
            }
        },
        //删除
        handleDelete (row, $index) {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                () => {
                    this.$set(this.checkLogList[$index], 'changeType', -1)
                    this.checkLogListCopy.splice($index, 1)
                }
            )
        },
        //检查记录选择
        checkLogSelect (val) {
            this.checkLog = val
        },
        //============进出场记录===========
        /**新增 */
        turnoverLogAdd () {
            openAppClient(
                `/outAccountTurnoverLogAdd?billid=${this.billid}&isNewAdd=true`,
                '外协台账进出场记录新增',
                () => {
                    this.getTurnoverRecord()
                },
                null,
                () => {
                    this.getTurnoverRecord()
                }
            )
        },
        //编辑
        turnoverLogEdit () {
            if (this.turnoverLog.length > 1) {
                this.clientPop('err', '一次只能选择一条数据！')
            } else {
                this.setAuditParams({ id: this.turnoverLog[0].accessRecordId })
                openAppClient(
                    `/outAccountTurnoverLogAdd?billid=${this.billid}&isNewAdd=false`,
                    '外协台账进出场记录编辑',
                    () => {
                        this.getTurnoverRecord()
                    },
                    null,
                    () => {
                        this.getTurnoverRecord()
                    }
                )
            }
        },
        //删除
        handleTurnoverDelete (row, $index) {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                () => {
                    this.$set(this.turnoverLogList[$index], 'changeType', -1)
                    this.turnoverLogListCopy.splice($index, 1)
                }
            )
        },
        //进出场记录选择项
        turnoverLogSelect (val) {
            this.turnoverLog = val
        },
        //============按钮操作=============
        /**更新基本信息 */
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        request
                            .outAccountUpdate(this.formData)
                            .then(() => {
                                this.getInfo()
                                resolve()
                            })
                            .catch(err => {
                                reject(err)
                                this.setError('baseInfo')
                                this.scorllError()
                            })
                    } else {
                        reject()
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //进场验收基本信息新增/修改
        siteBaseInfoAdd () {
            return new Promise((resolve, reject) => {
                this.$refs.formSite.validate(valid => {
                    if (valid) {
                        if (this.isNewAdd) {
                            //判断是新增还是修改
                            request
                                .outAccountAcceptorBaseAdd(
                                    this.formSiteBaseInfo
                                )
                                .then(res => {
                                    //新增
                                    this.formSiteBaseInfo = res
                                    resolve()
                                })
                                .catch(err => {
                                    reject(err)
                                    this.setError('siteBaseInfo')
                                    this.scorllError()
                                })
                        } else {
                            request
                                .outAccountAcceptorBaseUpdate(
                                    this.formSiteBaseInfo
                                )
                                .then(res => {
                                    //修改
                                    this.formSiteBaseInfo = res
                                    resolve()
                                })
                                .catch(err => {
                                    reject(err)
                                    this.setError('siteBaseInfo')
                                    this.scorllError()
                                })
                        }
                    } else {
                        reject()
                        this.setError('siteBaseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //检查记录更新
        checkRecordUpdate () {
            request.outAccountCheckRecordUpdate(this.checkLogList).then(res => {
                this.checkLogListCopy = [...res]
                this.checkLogList = res
                // this.getCheckLog()
            })
        },
        //进出场记录更新
        turnoverRecordUpdate () {
            request
                .outAccountTurnoverRecordUpdate(this.turnoverLogList)
                .then(res => {
                    this.turnoverLogListCopy = [...res]
                    this.turnoverLogList = res
                })
        },
        planTableSelect () {},
        //保存全部数据
        async saveAll () {
            //获取上传的对象
            let res = await ossRequest.getObjectByRelationId({
                relationId: this.billid
            })
            if (res.length === 0) {
                this.setError('attach')
                this.scorllError()
                this.clientPop('err', '进场验收必须上传附件！')
                return
            }
            Promise.all([
                this.updateBaseInfo(),
                this.siteBaseInfoAdd(),
                this.checkRecordUpdate(),
                this.turnoverRecordUpdate()
            ])
                .then(() => {
                    this.clientPop('suc', '保存成功')
                })
                .finally(() => {
                    hideLoading()
                })
        },
        //删除单据
        deleteBillid () {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                () => {
                    request.outAccountDelete(this.billid).then(() => {
                        this.clientPop('suc', '删除成功', this.handleClose)
                    })
                }
            )
        },
        //取消
        handleClose () {
            this.$router.replace('/outAccountList')
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight =
                        document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        }
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}
.childTab {
    ::v-deep .el-tabs__header {
        position: absolute !important;
    }
    ::v-deep .el-tabs__content {
        padding: 0 0 0 20px !important;
    }
}
.childTab1 {
    ::v-deep .el-tabs__header {
        position: absolute !important;
        .el-tabs__nav-scroll {
            position: relative;
            .el-tabs__nav {
                position: fixed;
                top: 0;
                width: 190px;
            }
        }
    }
}
.childTab2 {
    ::v-deep .el-tabs__header {
        position: absolute !important;
        .el-tabs__nav-scroll {
            position: relative;
            .el-tabs__nav {
                position: absolute;
                bottom: 0;
                width: 100%;
            }
        }
    }
}
</style>
